<template>
  <div :class="{ border }">
    <Toolbar
      class="toolbar"
      :class="{ 'toolbar-border': border }"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      :style="{ height: column?.style.height || height, 'overflow-y': 'auto' }"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="onCreatedEditor"
      @onChange="onChangeEditor"
    />
  </div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor'

const props = withDefaults(
  defineProps<{
    height?: string
    border?: boolean
    placeholder?: string
    modeValue: string
    beforeGetHtml?: () => any
    isSubmit?: boolean
    fieldName?: string
    column?: () => any
  }>(),
  {
    height: '500px',
    border: true,
    isSubmit: false,
    placeholder: '请输入内容',
    fieldName: 'fieldName',
  },
)

const mode = ref('default')
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML
const valueHtml = ref('')

// 模拟 ajax 异步获取内容
onMounted(async () => {
  console.log(props.column, 66)
  if (typeof props.beforeGetHtml === 'function') {
    valueHtml.value = await props.beforeGetHtml()
  }
  if (props.column.style.tool.length > 0) {
    toolbarConfig.toolbarKeys = props.column.style.tool
    console.log(props.column.style.tool, 7777)
  }
})

watch(
  () => props.isSubmit,
  (value: boolean) => {
    if (value) {
      editorRef.value.getElemsByType('image')
    }
  },
)

// 工具栏配置
const toolbarConfig: Partial<IToolbarConfig> = {
  // toolbarKeys: [],
  excludeKeys: [
    'group-video',
    'emotion',
    'insertVideo',
    'uploadVideo',
    'editVideoSize',
    'group-image',
    'insertTable',
    'undo',
    'redo',
    'fullScreen',
    'blockquote',
  ],
}
const editorConfig: Partial<IEditorConfig> = {
  placeholder: props.placeholder,
  MENU_CONF: {
    uploadImage: {
      server: '6666',
      fieldName: props.fieldName,
      // 小于该值就插入 base64 格式（而不上传），默认为 0
      base64LimitSize: 5 * 1024, // 5kb
      onBeforeUpload: (file: File) => onBeforeUpload(file),
      onProgress: (progress: number) => onProgress(progress),
      onSuccess: (file: File, res: any) => onUploadSync(file, res),
      onFailed: (file: File, res: any) => onUploadSync(file, res),
      onError: (file: File, err: any) => onUploadSync(file, err),
    },
    insertImage: {
      onInsertedImage(imageNode: HTMLImageElement | null) {
        if (imageNode == null) return

        const { src, alt, url, href } = imageNode
        console.log('inserted image', src, alt, url, href)
      },
      checkImage: () => {}, // 也支持 async 函数
      parseImageSrc: () => {}, // 也支持 async 函数
    },
  },
}
const onBeforeUpload = (file: File) => {}
// 上传进度的回调函数
const onProgress = (progress: number) => {
  // progress 是 0-100 的数字
  console.log('progress', progress)
}
// 单个文件上传成功之后
const onUploadSync = (file: File, res: any) => {
  console.log(`${file.name} 上传成功`, res)
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const onCreatedEditor = (editor: IDomEditor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

const $emit = defineEmits<{
  (e: 'update:value', val: string): any
}>()
const onChangeEditor = (value: IDomEditor) => {
  $emit('update:value', value.getHtml())
}
</script>
<style scoped lang="scss">
.border {
  border: 1px solid #ccc;
  width: 100%;
}

.toolbar {
  background-color: #fafafa;
  //border: 1px solid #ccc;
  //height: 100%;
  //width: 50px;
  //float: right;
}

.toolbar-border {
  border-bottom: 1px solid #ccc;
}
</style>
